/*****************************************************************************
 * Copyright (c) 2010 -, Anders All rights reserved
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 *  Contact: Anders Uddenberg (anders.uddenberg@gmail.com)
 * 
 *
 ****************************************************************************/
package org.easypr.organizer.server;

import com.google.gwt.user.client.rpc.IncompatibleRemoteServiceException;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.server.rpc.RPC;
import com.google.gwt.user.server.rpc.RPCRequest;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Singleton;

// TODO: Auto-generated Javadoc
/**
 * The Class GuiceRemoteServiceServlet.
 */
@Singleton
public class GuiceRemoteServiceServlet extends RemoteServiceServlet {
	
	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = -4127549458768107660L;

/** The injector. */
@Inject
  private Injector injector;

  /* (non-Javadoc)
   * @see com.google.gwt.user.server.rpc.RemoteServiceServlet#processCall(java.lang.String)
   */
  @Override
  public String processCall(String payload) throws SerializationException {
    try {
      RPCRequest req = RPC.decodeRequest(payload, null, this);

      RemoteService service = getServiceInstance(
            req.getMethod().getDeclaringClass());

      return RPC.invokeAndEncodeResponse(service, req.getMethod(),
        req.getParameters(), req.getSerializationPolicy());
    } catch (IncompatibleRemoteServiceException ex) {
      log("IncompatibleRemoteServiceException in the processCall(String) method.",
          ex);
      return RPC.encodeResponseForFailure(null, ex);
    }
  }

  /**
   * Gets the service instance.
   *
   * @param serviceClass the service class
   * @return the service instance
   */
  @SuppressWarnings({"unchecked"})
  private RemoteService getServiceInstance(Class serviceClass) {
    return (RemoteService) injector.getInstance(serviceClass);
  }
}